<template>
  <div class="loginContainer">
    <el-card header="欢迎来到登录页">
      <el-form
        :model="formData"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="formData.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="formData.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="submitForm('ruleForm')"
            >登录</el-button
          >
          <el-button @click="resetForm" type="info">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import {login} from "../api/users";
export default {
  data() {
    return {
      formData: {
        username: "",
        password: "",
      },
      rules: {
        username: [{ required:true,message:"用户名不能为空", trigger: "blur" }],
        password: [{ required:true,message:"密码不能为空", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.formData)
          .then(({data}) =>{
              let res = data;
              if(res.code ===1000){
                  localStorage.setItem("accessToken",data.data.token);
                  localStorage.setItem("refreshToken",data.data.refreshToken);
                  localStorage.setItem("userId",data,data.userId)
                   var tokenuserid = JSON.stringify(data.data.userId)
                   localStorage.setItem("userId",tokenuserid)
                  this.$router.push("/");
              }else{
                  this.$message({type:'error',message:res.ms});

              }
          })
          .catch((err)=>{
              console.log(err);
              this.$message({type:'error',message:err});
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.$router.push('/Register');
    },
  },
};
</script>
<style scoped>
.loginContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color:whitesmoke;
}
.el-card__header{
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 25px;
}
.el-card__body{
    width: 380px;
}
</style>